var server = require('http').createServer(),
	url = require('url'),
	WebSocketServer = require('ws').Server,
	wss = new WebSocketServer({
		server: server
	}),
	express = require('express'),
	app = express(),
	port = 4080;

app.use(function(req, res) {
	res.send({
		msg: "hello"
	});
});


//广播  
wss.broadcast = function broadcast(s, ws) {
	// console.log(ws);  
	// debugger;  
	wss.clients.forEach(function each(client) {
		// if (typeof client.user != "undefined") { 
		if(s == 1) {
			client.send( JSON.stringify(ws) );
		} else if(s == 0){
			ws.msg = '退出聊天室';
			client.send( JSON.stringify(ws) );
		}
		// }  
	});
};

// 初始化  
wss.on('connection', function connection(ws) {

	// console.log(ws.clients.session);  
	// console.log("在线人数", wss.clients.length);  
	// console.log(wss.clients);
	//ws.send('{"msg": "你是第' + wss.clients.length + '位"}');
	// 发送消息  
	ws.on('message', function(jsonStr, flags) {
		var obj = eval('(' + jsonStr + ')');
		// console.log(obj);  
		this.user = obj;
		//if(typeof obj.msg != "undefined") {
			wss.broadcast(1, obj);
		//}
	});
	// 退出聊天  
	ws.on('close', function(close) {
		try {
			wss.broadcast(0, this.user);
		} catch(e) {
			console.log('刷新页面了');
		}
	});

});

server.on('request', app).listen(port, function() {
	console.log('Listening on ' + server.address().port)
});